package com.air.ota.service.imp;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.air.common.util.QueryCondition;
import com.air.common.util.QueryExpression;
import com.air.ota.mo.InboundMsg;
import com.air.ota.mo.OutboundMsg;
import com.air.ota.service.ICardSequenceService;
import com.air.ota.service.IInboundMsgService;
import com.air.ota.service.IOutboundMsgService;
import com.air.ota.service.IPkgSequenceService;
import com.air.ota.service.ISMGPService;
import com.air.ota.util.ConfigProperties;
import com.air.ota.util.HexStringUtil;
import com.air.ota.vo.MsgListCacheVO;
import com.air.ota.vo.UTKBaseDownlinkVO;
import com.shouyi.SMGP_API.Sms;
import com.shouyi.SMGP_API.SmsClient;

@Service("smgpService")
public class SMGPServiceImp implements ISMGPService {
	
	@Autowired
	IInboundMsgService inboundMsgService;
	@Autowired
	IOutboundMsgService outboundMsgService;
	
	
	@Autowired
	IPkgSequenceService pkgSequenceService;
	@Autowired
	ICardSequenceService cardSequenceService;
	
	private SmsClient smsClient; 
	
	@Override
	@PostConstruct
	public void login() {
		smsClient = new SmsClient();
		String host =ConfigProperties.getInstance().getValue("smgp.host");
		int port = Integer.parseInt(ConfigProperties.getInstance().getValue("smgp.port"));
		String userName=ConfigProperties.getInstance().getValue("smgp.userName");
		String pwd=ConfigProperties.getInstance().getValue("smgp.pwd");
		int timeout = Integer.parseInt(ConfigProperties.getInstance().getValue("smgp.timeout"));
		
		int loginResult = smsClient.Login(host, port, userName,pwd, timeout);
		
		if (loginResult == 0) {
			System.out.println("--------SMGP login success");
		} else { 
			System.out.println("--------SMGP login fail");
		}
		
	}
	
	
	
	@Override
	public void sendSms(String tel,String contentHex){
		StringBuilder msgID = new StringBuilder();
		String srcNum =ConfigProperties.getInstance().getValue("smgp.srcNum");
		String pid =ConfigProperties.getInstance().getValue("smgp.pid");
		String udhi =ConfigProperties.getInstance().getValue("smgp.udhi");
		String msgType =ConfigProperties.getInstance().getValue("smgp.msgType");
		String msgFormat =ConfigProperties.getInstance().getValue("smgp.msgFormat");
		
		int[] sendResult = null;
		
		for(int i=0;i<10;i++){
			sendResult = smsClient.SendSms(srcNum,tel,contentHex, true, msgID,pid,udhi,msgType,msgFormat);
			if (sendResult[0]==0){
				break;
			}
			System.out.println("send SMS error RETRY code="+sendResult[0]);
		}
		
		for (int i = 0; i < sendResult.length; i++) {
			if (sendResult[i] == 0) {
				System.out.println("send SMS success");
			} else {
				System.out.println("send SMS error code="+sendResult[i]);
			}
		}
		
		
	}
	
	@Scheduled(cron = "0/2 * * * * *")
	public void scanDeliver() throws Exception{
		ArrayList<Sms> smsDeliverList = new ArrayList<Sms>();
		smsClient.RecvSms(smsDeliverList);
		InboundMsg inboundMsg;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		
		if (!smsDeliverList.isEmpty()) {
			System.out.println(sdf.format(new Date())+" RECEVIE SMS size="+smsDeliverList.size());
			for (Sms de : smsDeliverList) {
				inboundMsg = new InboundMsg();
				inboundMsg.setContent(HexStringUtil.bytesToHexString(de.getMsgContentBytes()));
				inboundMsg.setPhoneNumber(de.getSrcTermID().trim());
				inboundMsg.setSource(0);
				inboundMsg.setReceiveDate(System.currentTimeMillis());
				inboundMsgService.insert(inboundMsg);
			}
		}	
	}
	
	@Scheduled(cron = "0/1 * * * * *")
	public void scanInboundMsg() throws HttpException, IOException{
		
		InboundMsg inboundMsg=  MsgListCacheVO.popInboundMsg();
		if (inboundMsg!=null){
			HttpClient client = new HttpClient();
			HttpMethod method =new GetMethod("http://localhost:8080/ota/inboundMsg/process/"+inboundMsg.getId()+"/");
			
			client.executeMethod(method);
			//打印服务器返回的状态
		       System.out.println(method.getStatusLine());
		      //打印返回的信息
		      //System.out.println(method.getResponseBodyAsString());
			method.releaseConnection();
		}else{
			//System.out.print("NO InoubdMSG");
		}
	} 
	
	@Scheduled(cron = "0/1 * * * * *") 
	public void scanOutboundMsg(){
		
		OutboundMsg outboundMsg=  MsgListCacheVO.popOutboundMsg();
		if (outboundMsg!=null){
			System.out.println("Ready to Send SMS tel="+outboundMsg.getPhoneNumber()+" ContentHex="+outboundMsg.getContent());
			sendSms(outboundMsg.getPhoneNumber(),outboundMsg.getContent());
		}else{
			//System.out.print("NO OutoubdMSG");
		}
	}
	
	//@Scheduled(fixedDelay = 5*1000)
	public void resendOutbountMsg(){
		
		QueryCondition condition = new QueryCondition();
		condition.addQueryCondition("needRetry", 1, QueryExpression.EQUALS);
		condition.addQueryCondition("sendDate", System.currentTimeMillis()-(60*1000), QueryExpression.LT);
		
		List<OutboundMsg> msgList =this.outboundMsgService.queryByCondition(condition);
		for(OutboundMsg msg:msgList){
			/*byte[] cardSequence=null;
			try {
				cardSequence = HexStringUtil.hexStringToBytes(this.cardSequenceService.findByPhoneNum(msg.getPhoneNumber()).getCardSequence());
			} catch (Exception e) {
				e.printStackTrace();
			}
			UTKBaseDownlinkVO resendDownlingVO = UTKBaseDownlinkVO.updatePkgSequence(cardSequence, pkgSequenceService.getNextSequence(msg.getPhoneNumber()), msg.getContent());
			msg.setContent(HexStringUtil.bytesToHexString(resendDownlingVO.buildPkg()));*/
			
			this.sendSms(msg.getPhoneNumber(),msg.getContent());
			System.out.println("Retry  Send  SMS Complete,transid="+msg.getTransId()+", msgId="+msg.getId());
			//release retry lock
			msg.setNeedRetry(0);
			msg.setSendDate(System.currentTimeMillis());
			this.outboundMsgService.updateById(msg);
		}
		
		
	}
	
	
	public void sendTxtSMS(String tel,String content){
		StringBuilder msgID = new StringBuilder();
		String srcNum =ConfigProperties.getInstance().getValue("smgp.srcNum");
		String pid ="null";
		String udhi ="null";
		String msgType ="6";
		String msgFormat ="8";
		
		byte[] contentBytes=null;
		try {
			contentBytes = content.getBytes("utf-16BE");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String contentBytesStr = HexStringUtil.bytesToHexString(contentBytes);
		
		int[] sendResult = smsClient.SendSms(srcNum,tel,contentBytesStr, true, msgID,pid,udhi,msgType,msgFormat);
		for (int i = 0; i < sendResult.length; i++) {
			if (sendResult[i] == 0) {
				System.out.println("send SMS success");
			} else {
				System.out.println("send SMS error code="+sendResult[i]);
			}
		}
	}
	
}
